<template>
  <div class="goods-image">
    <!-- 二倍图 -->
    <div class="large" v-show="showLarge">
      <img
        v-src="pictures[currentIndex]"
        alt=""
        :style="{ top: bigPos.y + 'px', left: bigPos.x + 'px' }"
      />
    </div>
    <!-- 主图 -->
    <div class="middle" ref="target">
      <img v-src="pictures[currentIndex]" alt="" />
      <!-- 遮罩层 -->
      <div
        class="layer"
        v-show="showLarge"
        :style="{
          top: layPos.y + 'px',
          left: layPos.x + 'px'
        }"
      ></div>
    </div>
    <!-- 小图 -->
    <ul class="small">
      <li
        v-for="(src, index) in pictures"
        :key="index"
        @click="currentIndex = index"
      >
        <img v-src="src" alt="" />
      </li>
    </ul>
  </div>
</template>

<script>
import { reactive, ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: { pictures: Array, default: () => [] },
  setup () {
    const currentIndex = ref(0)
    const showLarge = ref(false)
    const target = ref(null)
    const bigPos = reactive({ x: 0, y: 0 }) // 大图坐标
    const layPos = reactive({ x: 0, y: 0 }) // 遮罩层坐标

    const { elementX, elementY, isOutside } = useMouseInElement(target)

    // 监听是否显示
    watch(isOutside, val => (showLarge.value = !val))
    // 监听坐标变化
    watch([elementX, elementY], () => {
      if (isOutside.value) return
      bigPos.x = -elementX.value
      bigPos.y = -elementY.value
      layPos.x = elementX.value - 100
      layPos.y = elementY.value - 100
      if (elementX.value < 100) layPos.x = 0
      if (elementX.value > 300) layPos.x = 200
      if (elementY.value < 100) layPos.y = 0
      if (elementY.value > 300) layPos.y = 200
    })

    return { currentIndex, showLarge, target, bigPos, layPos }
  }
}
</script>

<style scoped lang="less">
.large {
  position: absolute;
  top: 0;
  left: 412px;
  width: 400px;
  height: 400px;
  box-shadow: 0 0 10px rgba(222, 245, 96, 0.1);
  background-repeat: no-repeat;
  background-size: 800px 800px;
  background-color: #f8f8f8;
  overflow: hidden;
  img {
    max-width: 800px;
    max-height: 800px;
    position: absolute;
    left: 0;
    top: 0;
  }
}
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(255, 243, 82, 0.349);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
